type ValidationRule = {
  required?: boolean;
  min?: number;
  max?: number;
  message: string;
};

type ValidationRules = Record<string, ValidationRule[]>;

type FormData = Record<string, string | number | any[]>;

type ValidationErrors = Record<string, string>;

export default function validateForm(
  data: FormData,
  rules: ValidationRules
): Promise<ValidationErrors> {
  return new Promise((resolve, reject) => {
    const errors: ValidationErrors = {};
    Object.entries(rules).forEach(([field, fieldRules]) => {
      fieldRules.forEach((rule) => {
        let fieldValue = data[field];
        // 如果字段是数字类型且规则中有min或max，则转换为数字
        if (
          (rule.min !== undefined || rule.max !== undefined) &&
          typeof fieldValue === "string"
        ) {
          fieldValue = Number(fieldValue);
        }
        if (
          rule.required &&
          (!fieldValue ||
            fieldValue === "" ||
            (Array.isArray(fieldValue) && fieldValue.length === 0))
        ) {
          errors[field] = rule.message;
        } else if (rule.min !== undefined) {
          if (
            (Array.isArray(fieldValue) && fieldValue.length < rule.min) ||
            (typeof fieldValue === "string" && fieldValue.length < rule.min) ||
            (typeof fieldValue === "number" && fieldValue < rule.min)
          ) {
            errors[field] = rule.message;
          }
        } else if (rule.max !== undefined) {
          if (
            (Array.isArray(fieldValue) && fieldValue.length > rule.max) ||
            (typeof fieldValue === "string" && fieldValue.length > rule.max) ||
            (typeof fieldValue === "number" && fieldValue >= rule.max)
          ) {
            errors[field] = rule.message;
          }
        }
        // 可以继续添加其他规则，如 email、regex 等
      });
    });

    if (Object.keys(errors).length > 0) {
      reject(errors);
    } else {
      resolve({});
    }
  });
}
